package com.mairuide.robot.question;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.robot.IKAnalyzer.WordsSegmentationService;
import com.mairuide.robot.participles.MParticiples;
import com.mairuide.robot.participles.MParticiplesService;

@Controller
@RequestMapping("/mquestion")
public class MQuestionController extends BaseController {
	
	@Autowired
	private MQuestionService mQuestionService;
	
	@Autowired
	private MParticiplesService mParticiplesService;
	
	@Autowired
	private WordsSegmentationService wordsSegmentationService;
	
	
	@RequestMapping(value = "/capacitynewadd",method = RequestMethod.GET)
    public Object capacity(ModelMap model,Integer qid){
		model.addAttribute("qid", qid);
        return "/account/capacitynewadd";
    }

	/**
	 * 常用战法分析共同账户查询
	 * 
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@RequestMapping(value = "/getAllQuestion", method = RequestMethod.POST)
	@ResponseBody
	public Object getAllQuestion(String keyword, PageSupport pageSupport, String sortName, String sortOrder) {
		Map<String, Object> result = new HashMap<String, Object>();
		Page<QueryMQuestion> page = mQuestionService.findQuestion4KeyWord(keyword, pageSupport.getPage(), sortName, sortOrder);
		result.put("total", page.getTotalElements());
		result.put("rows", page.getContent());
		return result;
	}
	
	/**
	 * 新增修改
	 * @param model
	 * @param id
	 * @param userType
	 * @return
	 */
	@ResponseBody
	@PostMapping("/addAndEditQuestion")
	public Object addAndEditQuestion(ModelMap model, @RequestBody QueryMQuestion qm) {
		if(null == qm) {
			return ERROR("保存失败");
		}
		Integer createId = super.getLoginUser().getId();
		if(qm.getQid() == null) {//新增
			//保存问题回答
			MQuestion mq = new MQuestion();
			mq.setCreateId(super.getLoginUser().getId());
			mq.setQuestion(qm.getQuestion());
			mq.setAnswer(qm.getAnswer());
			mq = mQuestionService.save(mq);
			//保存分词
			if(StringUtils.isNotEmpty(qm.getSbparticiples())) {
				String[] sbpar = qm.getSbparticiples().split(",");
				for(String sbp : sbpar) {
					MParticiples mp = new MParticiples();
					if(sbp.contains("#")) {
						String[] q = sbp.split("#");
						mp.setParticiples(q[0]);//分词
						mp.setPriority(Integer.parseInt(q[1]));//优先级
					}else {
						mp.setParticiples(sbp);
						mp.setPriority(0);
					}
					mp.setCreateId(createId);
					mp.setCreateTime(new Date());
					mp.setQpId(mq.getqId());
					mParticiplesService.save(mp);
				}
			}
			return SUCCESS("保存成功");
		}else {//修改
			MQuestion oldMq = mQuestionService.findOne(qm.getQid());
			oldMq.setQuestion(qm.getQuestion());
			oldMq.setAnswer(qm.getAnswer());
			mQuestionService.save(oldMq);
			//先将原有分词删除然后重新生成
			mParticiplesService.deleteByQpId(qm.getQid());
			//保存分词
			if(StringUtils.isNotEmpty(qm.getSbparticiples())) {
				String[] sbpar = qm.getSbparticiples().split(",");
				for(String sbp : sbpar) {
					MParticiples mp = new MParticiples();
					if(sbp.contains("#")) {
						String[] q = sbp.split("#");
						mp.setParticiples(q[0]);//分词
						mp.setPriority(Integer.parseInt(q[1]));//优先级
					}else {
						mp.setParticiples(sbp);
						mp.setPriority(0);
					}
					mp.setCreateId(createId);
					mp.setCreateTime(new Date());
					mp.setQpId(qm.getQid());
					mParticiplesService.save(mp);
				}
			}
			return SUCCESS("修改成功");
		}
	}
	
	/**
	 * 编辑回显
	 * @param qm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/editQuestion",method = RequestMethod.POST)
    public Object editQuestion(@RequestBody QueryMQuestion qm){
		Map<String,Object> result = new HashMap<String,Object>();
		if(null !=  qm.getQid()) {
			MQuestion mq = mQuestionService.findOne(qm.getQid());
			List<MParticiples> participles = mParticiplesService.findByQpId(mq.getqId());
			List<String> ps = participles.stream().map(e -> e.getParticiples()+"#"+e.getPriority()).collect(Collectors.toList());
			result.put("mq", mq);
			result.put("participles", ps);
		}
		return result;
    }
	
	/**
	 * 删除操作
	 * @param qm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteQuestion",method = RequestMethod.POST)
    public Object deleteQuestion(@RequestBody QueryMQuestion qm){
		if(null !=  qm.getQid()) {
			mQuestionService.delete(qm.getQid());
			mParticiplesService.deleteByQpId(qm.getQid());
			return SUCCESS("删除成功");
		}
		return ERROR("删除失败");
    }
	
	
	/**
	 * 通过用户输入内容分词后查询回复内容
	 * @param chatSend
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getQuestion4Participles", method = RequestMethod.POST)
	public Object getQuestion4Participles(@RequestParam(defaultValue = "") String chatSend, HttpServletRequest request) {
		if(StringUtils.isEmpty(chatSend)) {
			return ERROR("chatSend is empy");
		}
		Map<String, Object> result = new HashMap<String, Object>();
		String qs = wordsSegmentationService.analyzer(chatSend.trim());
		List<MQuestion> mqs = mQuestionService.findQuestionByParticiples(qs);
		result.put("mqs", mqs);
		return result;
	}
	
	
}
